# -*- coding:utf-8 -*-

'''
PROJECT_NAME : auth_demo
file    : app4_jwt
author  : 1032162439@qq.com
date    : 2022-09-09 10:52
IDE     : PyCharm
'''

import datetime

from flask import Flask, jsonify, request
import jwt
from jwt import exceptions

app = Flask(__name__)

app.secret_key = 'secret key string!'


def create_token(payload):
    """
    生成token
    :param payload: 需要jwt携带的参数
    :return:
    """
    # 构造header
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    token = jwt.encode(payload=payload, key=app.secret_key, algorithm="HS256", headers=headers)
    return token


def get_payload(token):
    """
    根据token获取payload
    :param token:
    :return:
    """
    status = {'status': None, 'data': None}
    try:
        verified_payload = jwt.decode(jwt=token, key=app.secret_key, algorithms=['HS256'])
        status['status'] = True
        status['data'] = verified_payload
    except exceptions.ExpiredSignatureError:
        status['status'] = False
        status['data'] = 'token已过期'
    except jwt.DecodeError:
        status['status'] = False
        status['data'] = 'token验证失败'
    except jwt.InvalidTokenError:
        status['status'] = False
        status['data'] = '无效token'
    return status


@app.route('/gen_jwt')
def gen_jwt():
    """
    生成jwt视图函数
    :return:
    """
    payload = {
        'user_id': 1,
        'user_name': 'zs'
    }
    context = {
        'jwt': create_token(payload)
    }
    return jsonify(context)


@app.route('/source')
def source():
    """
    返回资源视图函数
    :return:
    """
    return '资源列表'


@app.before_request
def check_token():
    if request.path == '/gen_jwt':
        return
    token = request.args.get('token')
    result = get_payload(token)
    if not result['status']:
        return jsonify({'error': result['data']})
    print(f'当前访问的用户为{result["data"]["user_name"]}')
    return


if __name__ == '__main__':
    app.run(debug=True)
